//引入token
import { useUserStore, useTokenStore } from '@/stores'
//引入网络请求地址
import { baseUrl } from "./config";

//添加拦截器
const httpInterceptor = {
	//拦截前触发
	invoke(options : UniApp.RequestOptions) {
		// 非 http 开头需拼接地址
		if (!options.url.startsWith("http")) {
			options.url = baseUrl + options.url;
		}
		// 修改请求超时时间
		options.timeout = 60000;
		//添加token
		if (useTokenStore().accessToken) {
			options.header = {
				...options.header,
				Authorization: 'Bearer ' + useTokenStore().accessToken
				// Authorization: 'Bearer ' +'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImFjNzk0YmJmLTZjOWQtNGZhNi04NGM0LTNmYzAwYjM3MDU0MiJ9.LI4K8L-VaO0XUjl5DJ8uTiOd94Qvo8kGu-QnqTAxBgtHDUnMBvHOpO73S-m3ykMgeQawuCb0LFM2PoF06D6D-Q'
			}
		}
		// options.header = {
		// 	...options.header,
		// 	// Authorization: 'Bearer ' + useTokenStore().accessToken
		// 	Authorization: 'Bearer ' +'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImIxODMwYjJkLWViOTUtNGVkZS05MTM2LWQxZDZkMTkxZDBiOSJ9.5Co_spGbC4Mod5xNh4jBPkkRnZlq49j56vxotiFf5yswIuoakXFre_MF8gx0zaieJDt6Id2LkAf9D-em0SAzWQ'
		// }


	},
};

uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

/**
 * 请求函数
 * @param  UniApp.RequestOptions
 * @returns Promise
 */

// 添加类型，支持泛型
type Data<T> = {
	code : number
	msg : string
	data : T
}
export const service = <T>(options : UniApp.RequestOptions) => {
	//返回 Promise 对象
	return new Promise<Data<T>>((resolve, reject) => {
		uni.request({
			...options,
			// 响应成功
			success(res) {
				console.log(res,'返回的信息？')
				if (res.data.code == 401) {
					//用户过期操作
					uni.navigateTo({ url: '/pages/login/login' });
				}
				let result = res.data as Data<T>
				if (result.code !== 0 && result.code === 1) {
					uni.showToast({
						title: (res.data as Data<T>).msg || '请求错误',
						icon: 'none',
						duration: 1500
					})
					return reject(res.data)
				}
				resolve(res.data as Data<T>)
			},
			// 响应失败
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: '网络错误，换个网络试试',
				})
				reject(err)
			},
		})
	})
}